//
//  ViewController.m
//  Topic1
//
//  Created by 孙添凤 on 16/12/6.
//  Copyright © 2016年 孙添凤. All rights reserved.
//

#import "ViewController.h"
#import "Masonry.h"
#import "TopicObjModel.h"
#import "CreatTopicController.h"
#import "ChatController.h"
#import "TopicCell.h"
#import "MJRefresh.h"
#import "TestVoiceViewController.h"
#import   "UIImageView+WebCache.h"

@interface ViewController ()<UITableViewDelegate,UITableViewDataSource,UISearchBarDelegate,UISearchDisplayDelegate>{
    UITableView *tbview;
    UISearchBar  *  searchBar;
     UISearchDisplayController *  searchDc;
}
@property(nonatomic,strong)NSMutableArray *mutArr;
@property(nonatomic,assign)NSInteger a;
@property(nonatomic,assign)BOOL isRefresh;
@property(nonatomic,strong)NSMutableArray *systemArr;
@end

@implementation ViewController

static const CGFloat MJDuration = 0.5;
-(void)viewWillAppear:(BOOL)animated{
//    if(_mutArr.count>0){
//    [self dataRequest];
//    }
    
    [self loadNewData];
    self.cusTabView.hidden = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    _mutArr =[NSMutableArray array];
    [self setTitleLabelText:@"聊天室"];
    self.view.backgroundColor =[UIColor whiteColor];
    
    tbview =[[UITableView alloc]init];
    [self.view addSubview:tbview];
    [tbview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left);
        make.right.equalTo(self.view.mas_right);
        make.top.equalTo(self.view.mas_top);
        make.bottom.equalTo(self.view.mas_bottom);
    }];
    tbview.delegate = self;
    tbview.dataSource = self;
    tbview.separatorStyle = UITableViewCellSeparatorStyleNone;
    UIButton *RightNavBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    RightNavBtn.frame = CGRectMake(0, 0, 19, 16);
    [RightNavBtn setBackgroundImage:[UIImage imageNamed:@"add_message"] forState:UIControlStateNormal];
    [RightNavBtn addTarget:self action:@selector(RightClick:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *item = [[UIBarButtonItem alloc]initWithCustomView:RightNavBtn];
    self.navigationItem.rightBarButtonItem = item;
//    [self dataRequest];
    
    
    
    tbview.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self loadNewData];
    }];
    
    tbview.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [self footerRefresh];
    }];
    
    searchBar=[[UISearchBar  alloc] initWithFrame:CGRectMake(0.0f, 0.0f, KWIDTH, 44.0f)];
    searchBar.tintColor=[UIColor colorWithRed:0.8f green:0.8f blue:0.8f alpha:1.0f];
    searchBar.autocorrectionType=UITextAutocorrectionTypeNo;
    searchBar.autocapitalizationType=UITextAutocapitalizationTypeNone;
    searchBar.keyboardType=UIKeyboardTypeAlphabet;
    searchBar.hidden=NO;
    searchBar.placeholder=[NSString stringWithCString:"搜索"  encoding: NSUTF8StringEncoding];
    searchBar.delegate=self;
    tbview.tableHeaderView=searchBar;
    
    searchDc=[[UISearchDisplayController alloc] initWithSearchBar:searchBar contentsController:self];
    
    searchDc.searchResultsDataSource=self;
    searchDc.searchResultsDelegate=self;
    searchDc.delegate=self;
    
    UITextField *searchField=[searchBar valueForKey:@"_searchField"];
    searchField.backgroundColor =[UIColor whiteColor];
    searchField.layer.cornerRadius = 5;
    searchField.layer.borderWidth = 0.5;
    searchField.layer.borderColor = [[UIColor colorWithHex:0xdadbdf]CGColor];
    
    UIImage* searchBarBg = [self GetImageWithColor:[UIColor clearColor] andHeight:27.0f];
    //设置背景图片
    [searchBar setBackgroundImage:searchBarBg];
    //设置背景色
    [searchBar setBackgroundColor:[UIColor colorWithHex:0xefeff4]];
    //设置文本框背景
    [searchBar setSearchFieldBackgroundImage:searchBarBg forState:UIControlStateNormal];
    
    [searchDc  setActive:NO];
    
    
    
    
    
}


#pragma mark - Refresh
-(void)footerRefresh{
    [self.tbView.footer beginRefreshing];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(MJDuration * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        //*** setting edit style
        
        //        [self setStyle];
        
        // 刷新表格
        _a += 20;
        [self dataRequest];
        
        // 拿到当前的下拉刷新控件，结束刷新状态
        [tbview.footer endRefreshing];
    });
    
}

#pragma mark - setRithgAndUITableViewEditStyle
-(void)setStyle{
    self.tbView.editing = NO;
    //        [self.tbView reloadData];
}
#pragma mark - Refresh
-(void)loadNewData{
    
    
    [self.tbView.header beginRefreshing];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(MJDuration * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        //*** setting edit style
        
        [self setStyle];
        
        // 刷新表格
        _a = 0;
        _isRefresh = YES;
        [self dataRequest];
        
        // 拿到当前的下拉刷新控件，结束刷新状态
        [tbview.header endRefreshing];
    });
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.row!=0){
    TopicObjModel *model = [_mutArr objectAtIndex:indexPath.row-1];
     [self dataRequestWith:model];
    
//    ChatController *cv =[[ChatController alloc]init];
//    cv.pageID = model.T_17796_0;
//    cv.cusTabView = self.cusTabView;
////        TestVoiceViewController *cv =[[TestVoiceViewController alloc]init];
//    [self.navigationController pushViewController:cv animated:YES];
    }else{
        
    }
}

-(void)dataRequestWith:(TopicObjModel *)model{
    NSString *str = getUIStyle();
    NSMutableDictionary *param =[NSMutableDictionary dictionary];
    [param setObject:@"17798" forKey:@"tableId"]; //94 17798 7694
    [param setObject:@"7694" forKey:@"pageId"];
    [param setObject:@"17796" forKey:@"mainTableId"];//94 17796 7686
    
    if([str  isEqualToString:STYLE0]){
        [param setObject:@"17798" forKey:@"tableId"]; //94 17798 7694
        [param setObject:@"7694" forKey:@"pageId"];
        [param setObject:@"17796" forKey:@"mainTableId"];//94 17796 7686
        [param setObject:@"7686" forKey:@"mainPageId"];//教师7686 学员7991
    }else{
        [param setObject:@"17798" forKey:@"tableId"]; //94 17798 7694
        [param setObject:@"7993" forKey:@"pageId"];
        [param setObject:@"17796" forKey:@"mainTableId"];//94 17796 7686
        [param setObject:@"7991" forKey:@"mainPageId"];//教师7686 学员7991
    }
//    [param setObject:@"7686" forKey:@"mainPageId"];
    
    [param setObject:model.CHANNELID forKey:@"mainId"];
    [param setObject:@"20" forKey:@"limit"];
    [param setObject:@"0" forKey:@"start"];
    NSString *requestUrl =[NSString stringWithFormat:@"%@%@",BASE_URL,GOTOSCHOOL];
    [NetRequest requestUrl:requestUrl andParamas:param andReturnBlock:^(NSData *data, NSError *error) {
        if(data!=nil&&!error){
            NSDictionary *obj =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
            NSArray *arr = [obj objectForKey:@"rows"];
                ChatController *cv =[[ChatController alloc]init];
                cv.pageID = model.CHANNELID;
                cv.cusTabView = self.cusTabView;
            cv.customName = model.CUSTOMNAME;
            NSString * hhh = [obj objectForKey:@"total"];
            NSInteger ll = [hhh integerValue];
            cv.totleNum =ll;
            cv.totleNum2 =ll;
            //        TestVoiceViewController *cv =[[TestVoiceViewController alloc]init];
                [self.navigationController pushViewController:cv animated:YES];
            
        }else{
            
        }
    }];
    
}

-(void)RightClick:(UIButton *)btn{
    
    CreatTopicController *cv =[[CreatTopicController alloc]init];
    [self.navigationController pushViewController:cv animated:YES];
}

-(void)dataRequest{
    NSMutableDictionary *params =[NSMutableDictionary dictionary];
    
    NSString *str = getUIStyle();
    if([str  isEqualToString:STYLE0]){
        [params setObject:@"7686" forKey:@"pageId"];//教师7686 学员7991
    }else{
      [params setObject:@"7991" forKey:@"pageId"];//教师7686 学员7991
    }
    [params setObject:@"17796" forKey:@"tableId"];//94de 17796 7686  教师17796
    [params setObject:[NSString stringWithFormat:@"%ld",(long)_a] forKey:@"start"];
    [params setObject:@"20" forKey:@"limit"];
    NSString *requestUrl =[NSString stringWithFormat:@"%@%@",BASE_URL,LISTSVIEWREQUEST_URL];
    [NetRequest requestUrl:requestUrl andParamas:params andReturnBlock:^(NSData *data, NSError *error) {
        if(data!=nil&&!error){
            NSDictionary *obj =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
            NSLog(@"%@",obj);
            NSArray *arr =[obj objectForKey:@"dataList"];
            if(_isRefresh){
                [_mutArr removeAllObjects];
            }
            _isRefresh = NO;
//            [_mutArr removeAllObjects];
            for(NSDictionary *dic in arr){
                TopicObjModel *model =[[TopicObjModel alloc]init];
//                model.ObjName = [dic objectForKey:@"AFM_1"];
//                model.ObjCreatDate = [dic objectForKey:@"AFM_4"];
//                model.Members = [dic objectForKey:@"AFM_6"];
//                model.T_17796_0 =[dic objectForKey:@"T_17796_0"];
                model = [model initWithDictionary:dic error:nil];
                [_mutArr addObject:model];
            }
            [tbview reloadData];
            [self loadSystemMessage];
        }else{
            
        }
    }];
}



-(void)loadSystemMessage{
    NSMutableDictionary *params =[NSMutableDictionary dictionary];
    
    NSString *str = getUIStyle();
    if([str  isEqualToString:STYLE0]){
        [params setObject:@"8563" forKey:@"pageId"];//教师7686 学员7991
    }else{
        [params setObject:@"7991" forKey:@"pageId"];//教师7686 学员7991
    }
    [params setObject:@"17798" forKey:@"tableId"];//94de 17796 7686  教师17796
    
    NSString *requestUrl =[NSString stringWithFormat:@"%@%@",BASE_URL,GOTOSCHOOL];
    
    [NetRequest requestUrl:requestUrl andParamas:params andReturnBlock:^(NSData *data, NSError *error) {
        if(data!=nil&&!error){
            NSDictionary *obj =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
            NSLog(@"%@",obj);
            NSArray *arr =[obj objectForKey:@"rows"];
            _systemArr = [NSMutableArray arrayWithArray:arr];
            [tbview reloadData];
            
        }else{
            
        }
    }];
    
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSLog(@"%@",_mutArr);
    return _mutArr.count+1;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
//    TopicObjModel *model =[_mutArr objectAtIndex:indexPath.row];
//    UILabel *la =[[UILabel alloc]init];
//    la.text = model.AFM_6;
//    la.numberOfLines = 0;
//    float hh = [la sizeThatFits:CGSizeMake(KWIDTH-110, CGFLOAT_MAX)].height;//动态计算高度
//    return hh+60;
    return 73;
}

- (UIImage*) GetImageWithColor:(UIColor*)color andHeight:(CGFloat)height
{
    CGRect r= CGRectMake(0.0f, 0.0f, 1.0f, height);
    UIGraphicsBeginImageContext(r.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, r);
    
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return img;
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *str = @"str";
    TopicCell *cell =[tableView dequeueReusableCellWithIdentifier:str];
    if(cell==nil){
        cell=[[TopicCell alloc]initIdentifier:str];
    }
    if(indexPath.row!=0){
        cell.systemImg.hidden = YES;
        cell.systemTitle.hidden = YES;
        cell.sysNumLa.hidden = YES;
        cell.name.hidden = NO;
        cell.people.hidden = NO;
        cell.timeLa.hidden = NO;
        cell.numLa.hidden = YES;
        cell.img.hidden = NO;
        [cell.img sd_setImageWithURL:[NSURL URLWithString:@"http://imgsrc.baidu.com/forum/w=580/sign=8da0626cbc8f8c54e3d3c5270a2b2dee/f2df44391f30e9249a6838b344086e061f95f7b9.jpg"]];
//        [cell.img sd_setImageWithURL:[NSURL URLWithString:@"http://bailitianxia-edus.oss-cn-beijing.aliyuncs.com/2016-12-23/8765f3d3572c11df71c5ef7d652762d0f603c291.jpg?Expires=1482634687&OSSAccessKeyId=vGYn0xGpshJEzwyt&Signature=RULDLA7NIUCDQZRQuNXzcDWsTQU%3D"] placeholderImage:[UIImage imageNamed:@"default_portrait"]];

        TopicObjModel *model =[_mutArr objectAtIndex:indexPath.row-1];
        NSString *str = getUIStyle();
        if([str isEqualToString:STYLE0]){
            if(![model.CUSTOMNAME isEqualToString:@""]){
                cell.name.text = model.CUSTOMNAME;
            }else{
                cell.name.text = model.DEFAULTNAME;
            }
        }else{
            if(![model.CUSTOMNAME isEqualToString:@""]){
                cell.name.text = model.CUSTOMNAME;
            }else{
                cell.name.text = model.DEFAULTNAME;
            }
        }
        
       
        cell.people.text = model.CHANNELLATESTMESSAGE;
    }else{
        cell.systemImg.hidden = NO;
        cell.systemTitle.hidden = NO;
        cell.sysNumLa.hidden = NO;//系统消息红圈
        cell.name.hidden = YES;
        cell.people.hidden = YES;
        cell.timeLa.hidden = YES;
        cell.numLa.hidden = YES;
        cell.img.hidden = YES;
        if(_systemArr!=nil){
            cell.sysNumLa.text = [NSString stringWithFormat:@"%lu",(unsigned long)_systemArr.count];
        }

    }
    
    
    return cell;
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
